package connpool

import (
	"errors"
	"net"
	"sync"
)

var (
	Err_ConnNotFound = errors.New("connect is not found")
)

type ConnPool struct {
	lock sync.Mutex
	pool map[string]net.Conn
}

//初始化连接池
func (this *ConnPool) Init(gcInterval int64) {
	this.pool = make(map[string]net.Conn)
	this.beginConnGC(this.pool, gcInterval*1000)
}

func (this *ConnPool) Put(id string, conn net.Conn) error {
	this.lock.Lock()
	defer this.lock.Unlock()
	this.pool[id] = conn
	return nil
}

func (this *ConnPool) Get(id string) (net.Conn, error) {
	this.lock.Lock()
	defer this.lock.Unlock()
	v, ok := this.pool[id]
	if !ok {
		return nil, Err_ConnNotFound
	}
	return v, nil
}

func (this *ConnPool) Foreach(callback func(string)) {
	if this.pool != nil && len(this.pool) > 0 {
		for k := range this.pool {
			key := k
			callback(key)
		}
	}
}

func (this *ConnPool) Clear() {
	this.lock.Lock()
	defer func() {
		this.lock.Unlock()
		this.pool = nil
	}()
	for k := range this.pool {
		key := k
		this.pool[key].Close()
	}
}

func (this *ConnPool) Count() int {
	if this.pool == nil {
		return 0
	}
	this.lock.Lock()
	defer this.lock.Unlock()
	return len(this.pool)
}
